#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/9/2
# @Author  : YunZhen
# @File    : _parse.py
# @Software: PyCharm
"""
解析Python官网HTML，提取版本和下载链接
"""
import os
import re
import aiohttp
from bs4 import BeautifulSoup
from loguru import logger

# 平台映射表
PLATFORM_MAP = [
    os.getenv('LINUX'),
    os.getenv('WINDOWS'),
    os.getenv('MACOS')
]
PLATFORM_MAP = [p.lower() for p in PLATFORM_MAP if p]

PLATFORM_HOST, DOWNLOAD_URI = os.getenv('PYTHON_HOST'), os.getenv('DOWNLOAD_URI')
if not PLATFORM_HOST or not DOWNLOAD_URI:
    raise ValueError("环境变量 'PYTHON_DOWNLOAD_URLS' 未设置")


def _get_system_url_map(html: BeautifulSoup):
    """获取系统到URL的映射"""
    system_url_map = {}
    try:
        download = html.select('#downloads ul li a')
        for system in download:
            if system.text.lower() in PLATFORM_MAP:
                system_url_map[system.text.lower()] = system['href']
                logger.debug("系统类型: {}", system.text)
    except Exception as e:
        logger.error(f"解析版本URL时出错: {e}")
    logger.info("版本URL映射: {}", system_url_map)
    return system_url_map


def _get_version_url_map(html: BeautifulSoup):
    """获取版本到URL的映射"""
    logger.info("解析版本URL")
    python_version_packages = {}
    try:
        version_list = html.select('.col-row.two-col div')
        logger.debug("查找个版本区域")
        for version_element in version_list:
            if version_element.select_one('h2').text.strip().lower().startswith('stable'):
                version_table = version_element
                break
        else:
            raise ValueError("未找到稳定版本的下载链接, 检查页面结构是否变化")
        logger.debug("找到稳定版本区域，开始解析下载链接")
        # 查找所有下载链接
        python_item = version_table.find('ul', recursive=False)
        versions_list = python_item.find_all('li', recursive=False)
        for version_item in versions_list:
            # 解析版本号和发布日期
            version, data = version_item.find('a').text.strip().split('-')
            version = re.search(r'(\d+\.\d+\.\d+)', version.strip()).group(1)
            logger.debug("解析到版本: {}，发布日期: {}", version, data.strip())
            # 解析下载链接
            links_item = version_item.find('ul')
            version_links_dict = {}
            for links in links_item.select('a'):
                version_links_dict[links.text.strip()] = links['href']
                logger.debug("解析到下载链接: {} -> {}", links.text.strip(), links['href'])
            python_version_packages[version] = {
                'release_date': data.strip(),
                'links': version_links_dict
            }
        logger.info("版本解析完成")
    except Exception as e:
        logger.error(f"解析版本URL时出错: {str(e)}")
    logger.debug("解析到的版本信息: {}", python_version_packages)
    return python_version_packages


async def get_system_version_url_map(url: str, system: str, session: aiohttp.ClientSession):
    """获取指定系统的版本URL"""
    logger.info(f"获取系统 {system} 的Python版本URL: {url}")
    system_version_url_map = {}
    try:
        async with session.get(PLATFORM_HOST + url) as response:
            html = await response.text()
            logger.debug('打开页面: {}{}，响应成功', PLATFORM_HOST, url)
            soup = BeautifulSoup(html, 'html.parser')
            # 获取版本到URL的映射
            system_url_map = _get_version_url_map(soup)
            if system_url_map:
                system_version_url_map['linux' if system == 'source code' else system] = system_url_map
            else:
                logger.warning(f"未找到系统 {system} 的下载链接")

    except Exception as e:
        logger.error(f"获取系统版本URL时出错: {str(e)}")
    return system_version_url_map


async def get_all_python_versions_for_net():
    """获取所有历史Python版本"""

    async with aiohttp.ClientSession() as session:
        all_python_version_url_map = {}
        try:
            # 获取主下载页面
            async with session.get(PLATFORM_HOST + DOWNLOAD_URI) as response:
                html = await response.text()
                logger.debug('打开页面: {}，响应成功', PLATFORM_HOST, DOWNLOAD_URI)
                soup = BeautifulSoup(html, 'html.parser')

                # 获取不同系统下载URL映射
                system_url_map = _get_system_url_map(soup)
                # 遍历每个系统, 获取对应的版本下载url
                for system, url in system_url_map.items():
                    # 获取每个系统的版本页面
                    system_version_url_map = await get_system_version_url_map(url, system, session)
                    if system_version_url_map:
                        all_python_version_url_map.update(system_version_url_map)
        except Exception as e:
            logger.error(f"解析版本时出错: {str(e)}")
    return all_python_version_url_map
